package com.ymt.fmd.platform.web.action;

import com.ymt.fmd.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("/view/platform/fmd")
public class FormPreviewAction {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Environment env;

    @GetMapping("/preview")
    public ModelAndView preview(HttpServletRequest request,
                                @RequestParam("s")String skin,
                                @RequestParam("l")String lang,
                                @RequestParam("ff")String formFile,
                                @RequestParam("ft")String formType) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = getTenantId(userDetail);
        String[] profile = env.getActiveProfiles();
        String productionVersion = env.getProperty("bpmp.production-version", "0");
        String cdn = env.getProperty("bpmp.cdn", "/bpmp-resources");
        String ttag = "DATAEDIT".equalsIgnoreCase(formType) ? "e" : "";
        String path = "/jsp/formpreview/"+skin+"/"+ttag+"wrapper.jsp";
        String formfile = "/jsp/formpreview/"+skin+"/generated/"+tenantId+"/"+formFile;
        if (log.isDebugEnabled()) {
            log.debug("path="+path);
            log.debug("formfile="+formfile);
        }
        ModelAndView view = new ModelAndView(path);

        view.addObject("profile", profile[0]);
        view.addObject("productionVersion", productionVersion);
        view.addObject("cdn", cdn);
        view.addObject("cdnfmd", env.getProperty("fmd.cdn"));
        view.addObject("fmdCtx", env.getProperty("fmd.ctx"));
        view.addObject("bpmpCtx", env.getProperty("bpmp.site-url"));
        view.addObject("ctxPath", request.getContextPath());
        view.addObject("formfile", formfile);
        //view.addObject("dhxskin", env.getProperty("fmd.dhxskin"));
        view.addObject(Const.LANG, lang);

        return view;
    }

    /**
     * 由于tenantId存在于主键中，所以如果不存在则给一个默认值0
     * @return
     */
    private String getTenantId(Map<String, String> userDetail) {
        String tenantId = userDetail.get(Const.TENANT_ID);
        if (tenantId==null) {
            return "0";
        }
        return tenantId;
    }

}
